#!/usr/bin/python3
"""_summary_

    Raises:
        WebApiError: _description_

    Returns:
        _type_: _description_
    """
# -*- coding:utf-8 -*-
#
# File Name:
# @Author:  paddy
# @Email:   3988263@qq.com
# @Time:    ${DATE} ${TIME}
# Project: ${PROJECT_NAME}
# ---------------------说明--------------------------
#
# ---------------------------------------------------
import signal
from multiprocessing import Process
import logging
from service.mqtt_client import DeviceAttrib, MqttManager
from service.myconf import MyConfigParser
from service.base import MyBase
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
logger.addHandler(console)

threads = []
mqtt_list = []


class Manager(MyBase):
    """默认运行前提是必须有 business_name,business_id

    Returns:
        _type_: _description_
    """
    myconf: MyConfigParser = None

    def __init__(self, subwebapi, myconf):
        """_summary_

        Args:
            webapi (_type_): _description_
        """
        super().__init__(subwebapi)
        self.myconf = myconf

    def _generator_deviceattrib(self, device) -> DeviceAttrib:
        """ 初始化设备对象属性 """
        deviceattrib = DeviceAttrib()
        deviceattrib.device_id = device['device_id']
        deviceattrib.username = device['device_id']
        deviceattrib.token = device['access_token']
        deviceattrib.device_name = device['device_name']
        deviceattrib.asset_name = device['asset_name']
        deviceattrib.mqtt_host = self.myconf.get_config('Mqtt', 'MQTT_HOST')
        deviceattrib.mqtt_port = self.myconf.get_config('Mqtt', 'MQTT_PORT')
        deviceattrib.client_id = self.myconf.get_config('Mqtt', 'CLIENT')
        deviceattrib.topic = self.myconf.get_config('Mqtt', 'TOPIC')
        return deviceattrib

    def worker(self, device):
        # 开始启动单个设备的随机模拟数据 """
        deviceattrib = self._generator_deviceattrib(device)
        _mqtt_client_mm = MqttManager(
            self.webapi,
            deviceattrib
            )
        mqtt_list.append(_mqtt_client_mm)
        _mqtt_client_mm.start()

    def start(self):
        """开始随机循环多线程启动设备模拟数据
        """
        signal.signal(signal.SIGINT, keyboard_interrupt_handler)

        for _device in self.device_array:
            threads.append(
                Process(
                    target=self.worker,
                    args=(_device,)
                )

            )
        for thread in threads:
            thread.start()
        print("随机循环多线程启动设备模拟数据--完毕")


def keyboard_interrupt_handler(sys_signal, frame):
    """捕获键盘终止命令

    Args:
        sys_signal (_type_): _description_
        frame (_type_): _description_
    """
    if sys_signal or frame:
        pass
    print(f"接收终止命令，键盘信号 (ID: {sys_signal}) \
        停止和清理子线程..")
    for _mqtt_client_mm in mqtt_list:
        _mqtt_client_mm.disconnect()
    for thread in threads:
        thread.terminate()
